import {designPage, useStyleCache} from "@peryl/react-compose";
import {CmsEditor, createSimpleDate} from "../../packages";
import {useCmsEditorOption} from "../module/cms-visual-editor";
import {$notice, ClientZoom, i18n, Icon} from "plain-design";
import {RouteSelector} from "../components/RouteSelector";
import {upload} from "../module/plain-design/upload";
import {pathJoin} from "@peryl/utils/pathJoin";
import {env} from "../env";

export default designPage(() => {

  const option = useCmsEditorOption({
    isRunning: false,
    titleRightContent: () => <RouteSelector/>,
  });

  option.panelOperation.registry(8, 'preview', 'center', () => (
    <div className="cms-editor-panel-operation-button" onClick={async () => {
      const dataMetas = option.state.getStateData();
      // 创建 Blob 对象
      const blob = new Blob([JSON.stringify(dataMetas)], { type: "application/json" });
      const file = new File([blob], `cms.${createSimpleDate().YMDHms}.json`, {
        type: "application/json",
        lastModified: new Date().getTime()
      });
      await upload.upload({
        filename: 'file',
        file: file,
        onSuccess: (data: any) => {
          const filePath = pathJoin(env.assetsPrefix, data.result?.path);
          console.log(filePath);
          const url = new URL(window.location.href);
          url.pathname = pathJoin(__webpack_public_path__, '/cms-preview');
          url.searchParams.append('path', filePath);
          window.open(url.href);
          // AppRouter.history.push('/cms-preview', { path: filePath });
        },
        onError: (e: any) => {$notice.error(`文件上传失败：${e?.message || JSON.stringify(e)}`);},
      });
    }}><span><Icon icon="pi-eye"/></span><span>{i18n.$intl('cms.operation.preview').d('预览')}</span></div>
  ));

  // option.hooks.onUpdateData.use(() => {console.log('data change');});

  console.log({ option }, option.state.getStateData());

  import('./basic.data.json').then(resp => {option.methods.updateData(resp.default as any);});

  const styles = useStyleCache(style => {
    style.minHeight = `calc(100vh / ${ClientZoom.get()})`;
  });

  return () => (
    <CmsEditor option={option} style={styles.value}/>
  );
});
